import axios from "axios";
import qs from "qs";
import cookie from 'js-cookie';


// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = 'http://localhost:8090' //测试
axios.defaults.withCredentials = true
//post请求头
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;

axios.interceptors.request.use(
    config => {
        if(cookie.get('token')){
            config.headers['token'] = cookie.get('token');
        }
        //截取请求
        // if (config.url.indexOf('api.php') != -1) {
        //     config.baseURL = "http://api.qingyunke.com/";
        //     config.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';
        //     config.headers['Access-Control-Allow-Origin'] = '*';
        //     config.headers['Access-Control-Allow-Headers'] = '*';
        //     config.headers['Access-Control-Allow-Methods'] = '*';
        // }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        if (response.status == 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        console.log(error);
    }
);
export default {
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'post',
                    url,
                    data: qs.stringify(data),
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },

    get(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'get',
                    url,
                    params: data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
    put(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'put',
                    url,
                    params: data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
    delete(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'delete',
                    url,
                    params: data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
};